const electron = require('electron')
const os = require('os')
const path = require('path')
const fs = require('fs')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const Tray = electron.Tray
const Menu = electron.Menu
const dialog = electron.dialog
const ipcMain = electron.ipcMain
// var client = require('electron-connect').client
let win = null,
    child = null,
    tray = null,
    mainHtml = path.join(__dirname, 'index.html'),
    loginHtml = path.join(__dirname, 'login.html'),
    image_icon = path.join(__dirname, 'medical.png'),
    compelClose = false,
    jsonFile = path.join(__dirname, 'arguments.json'),
    expirationTime = 1//年
let fileText = {
    mac: getMac(),
    startTime: getDateYear(),
    doctor: '',
    text: [
        ['雪胆素胶囊','0.23g*24粒/盒','1盒','tid','2粒','口服','48'],
        ['舒服止痒酊','30ml/盒','1盒','tid','喷0.5ml','外用','70'],
        ['木竭胶囊','0.4g*27粒/盒','1盒','tid','3粒','口服','70'],
        ['熊胆开明片','0.46g*24片/盒','1盒','tid','4片','口服','80'],
        ['脾氨肽口服冻干粉','2ml*5支/盒','1盒','tid','1支','口服','120'],
        ['复方太子参颗粒','5g*10袋/盒','1盒','tid','1袋','口服','64'],
        ['小儿广朴止泻口服液','10ml*6支/盒','1盒','tid','5ml','口服','50'],
        ['延胡胃安胶囊','0.4g*24粒/盒','1盒','tid','1粒','口服','50'],
        ['亮菌口服溶液','10ml*10支/盒','1盒','tid','1支','口服','80'],
        ['补肾壮骨口服液','10ml*10支/盒','1盒','tid','1支','口服','64'],
        ['复方红衣补血口服液','10ml*18支/盒','1盒','tid','1支','口服','80'],
        ['小儿咳嗽糖浆','10ml/盒','1盒','tid','0.5ml','口服','50'],
        ['富马酸替诺福韦二吡呋酯片','0.3g*30片/盒','1盒','tid','1片','口服','440'],
        ['肾安胶囊','0.4g*24粒/盒','1盒','tid','2粒','口服','70'],
        ['羊藿三川颗粒','7.5g*6袋/盒','1盒','tid','1袋','口服','70'],
        ['小儿咳喘颗粒','6g*6袋/盒','1盒','tid','3g','口服','60'],
        ['复方乌鳢口服液','10ml*10支/盒','1盒','tid','1支','口服','110'],
        ['亮菌口服溶液(无糖型)','10ml*10支/盒','1盒','tid','1支','口服','80'],
        ['鲑鱼降钙素喷鼻剂','2ml*0.25mg/盒','1盒','tid','喷鼻2次','外用','220'],
        ['虫草头孢菌胶囊','0.25g*50粒/盒','1盒','tid','3粒','口服','100'],
        ['鼻宁喷雾剂','10ml/盒','1盒','tid','喷鼻3次','外用','80'],
        ['小牛血清去蛋白肠溶胶囊','0.25mg*24粒/盒','1盒','tid','4粒','口服','300'],
        ['甲芪肝纤颗粒','4g*15袋/盒','1盒','tid','1袋','口服','170'],
        ['蒲苓盆炎康颗粒','10g*9袋/盒','1盒','tid','1袋','口服','60'],
        ['胸腺蛋白口股溶液','6ml:30mg/6瓶/盒','1盒','tid','1瓶','口服','120'],
    ],
}
function createWindow() {
    let browser = {
        width: 600,
        height: 800,
        center: true,
        resizable: true,
        movable: true,
        minWidth: 400,
        minHeight: 700,
        minimizable: true,
        maximizable: true,
        icon: image_icon,
        backgroundColor: '#fff',
    }
    win = new BrowserWindow(browser)
    win.loadFile(mainHtml)
    win.setMenu(null)
    win.once('ready-to-show', () => {
        win.show()
    })
    win.on('unresponsive', () => {
        //网页变得未响应时重启应用
        app.relaunch({args: process.argv.slice(1).concat(['--relaunch'])})
        app.exit(0)
    })
    win.on('close', (e) => {
        // if (!compelClose) {
        //     //如果不是强制关闭, 阻止默认动作
        //     e.preventDefault()
        //     win.hide()
        // }
    })
    //调试
    // win.webContents.openDevTools()
}
app.on('ready', () => {
    createWindow()
    loginBrowserWindow()
    //gulp配置的调试代码实时更新页面
    // client.create(win)
    //监听ipc事件
    monitor_ipc()
    //设置托盘
    // setTray()
    //读取数据
    readFiles()
    //保证单一实例
    closeSecondInstance()
})
app.on('activate', () => {
    if (win === null) {
        createWindow()
    }
})
app.on('window-all-closed', () => {
    app.quit()
})
function loginBrowserWindow() {
    let browser = {
        parent: win,
        modal: true,
        center: true,
        resizable: false,
        movable: false,
        icon: image_icon,
        backgroundColor: '#fff',
    }
    child = new BrowserWindow(browser)
    child.loadFile(loginHtml)
    child.setMenu(null)
    win.hide()
    child.once('ready-to-show', () => {
        child.show()
    })
    child.on('unresponsive', () => {
        //网页变得未响应时重启应用
        app.relaunch({args: process.argv.slice(1).concat(['--relaunch'])})
        app.exit(0)
    })
    child.on('close', function() {
        app.quit()
    })
}
/**
 * 保证单一实例
 * @return {[type]} [description]
 */
function closeSecondInstance() {
    //判断是否是第二实例, 如果是 退出(保证单一实例)
    let myWindow = win
    const isSecondInstance = app.makeSingleInstance((commandLine, workingDirectory) => {
    if (myWindow) {
        if (myWindow.isMinimized()) myWindow.restore()
            myWindow.focus()
        }
    })
    if (isSecondInstance) {
        compelClosed()
    }
}
/**
 * 设置托盘属性
 */
function setTray() {
    //设置托盘图标
    tray = new Tray(image_icon)
    let trayMenuTemplate = [
        {
            label: '退出',
            click () {
                compelClosed()
            }
        }
    ]
    let contextMenu = Menu.buildFromTemplate(trayMenuTemplate)
    tray.setContextMenu(contextMenu)
    tray.setToolTip('处方笺')
    tray.on('click', () => {
        win.show()
    })
}
/**
 * 读取数据
 * @return {[type]} [description]
 */
function readFiles() {
    fs.readFile(jsonFile, (err, data) => {
        if (err){console.error(err)}
        //读取文件, 如果不存在数据则输入数据(初始化), 如果存在数据则覆盖fileText
        if (data.toString()) {
            fileText = chaos_decode(data.toString())
            console.log('数据读取成功')
            judge_authority(true)
        } else {
            judge_authority(false)
        }
    })
}
/**
 * 根据json文件数据判断权限
 * @param  {[type]} arg [description]
 * @return {[type]}     [description]
 */
function judge_authority(arg) {
    if (!arg){
        writeFiles()
    }
    //是否同一电脑使用
    isSecondMac(fileText)
    //是否过期
    isExpiration(fileText)
}
/**
 * 写入数据
 * @return {[type]} [description]
 */
function writeFiles() {
    fs.writeFile(jsonFile, chaos_encode(fileText), (err) => {
        if (err){console.error(err)}
        console.log('数据写入成功')
    })
}
/**
 * 是否同一电脑使用
 * @param  {json}  data json文件数据
 * @return {Boolean}      [description]
 */
function isSecondMac(data) {
    if (data.mac != getMac()) {
        dialog.showErrorBox('启动失败', '该软件已在其他电脑使用过, 一个软件只能在一台电脑使用!')
        compelClosed()
    }
}
/**
 * 是否过期
 * @param  {json}  data json文件数据
 * @return {[type]} [description]
 */
function isExpiration(data) {
    if (data.startTime != getDateYear()){
        //不是同一年
        dialog.showErrorBox('软件已过期', '该软件使用有效期1年, 您的软件使用权限已过期, 请重新购买')
        compelClosed()
    }
}
/**
 * 获取当前电脑网卡的IPv4 mac地址
 * @return {string} IPv4 mac地址
 */
function getMac() {
    //获取电脑网卡mac地址
    let interfaces = os.networkInterfaces()
    for (let devName in interfaces) {
        var iface = interfaces[devName]
        for (let face of iface) {
            if (face.family == 'IPv4' && face.address != '127.0.0.1' && !face.internal) {
                return face.mac
            }
        }
    }
}
/**
 * 获取当前年份
 * @return {int} 年份
 */
function getDateYear() {
    let date = new Date()
    var year = date.getFullYear()
    return year
}
/**
 * 加密
 * @param  {json} data json文件数据
 * @return {string}      加密过的json文件数据
 */
function chaos_encode(data) {
    let buf = Buffer.from(JSON.stringify(data))
    let res = buf.toString('hex')
    return res
}
/**
 * 解码
 * @param  {string} data 加密过的json文件数据
 * @return {json}      解码后json文件数据
 */
function chaos_decode(data) {
    let buf = Buffer.from(data, 'hex')
    let res = JSON.parse(buf.toString())
    return res
}
/**
 * 强制退出
 * @return {[type]} [description]
 */
function compelClosed() {
    compelClose = true
    app.quit()
}
/**
 * 监听主进程与渲染进程的异步通信
 * @return {[type]} [description]
 */
function monitor_ipc() {
    //接受渲染进程打印事件与参数
    ipcMain.on('click_print', (event, arg) => {
        fileText.doctor = arg
        writeFiles()
        win.webContents.print({silent: false, printBackground: false, deviceName: ''}, () => {
            console.log('打印成功-----')
            win.reload()
        })
    })
    //接受渲染进程请求事件,读取文本并回复
    ipcMain.on('request_fileText', (event, arg) => {
        readFiles()
        event.sender.send('reply_fileText', fileText)
    })
    ipcMain.on('login_request', (event, arg) => {
        child.hide()
        win.show()
    })
    ipcMain.on('click_reload', (event, arg) => {
        win.reload()
    })
}